<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Admin\Cat;
class CatController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // return 1;
        $data = Cat::all();
        // dd($data);
        $cats = $this->findTree($data,0,0);
      
        // dd($cats);
        return view("admin.cat_index")->with('cats',$cats);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $data = Cat::all();
        $cats = $this->findTree($data,0,0);        
        return view("admin.cat_add")->with('cats',$cats);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //验证
        $cats = new cat();
        $cats->cats_pid=$request->cats_pid;
        $cats->cats_name = $request->cats_name;
        $cats->save();
       return redirect('/cat');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('admin.cat_edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    /**
     * @param  [type] $data
     * @param  integer $id
     * @param  integer $lev
     *找子孙栏目
     * @return [type]
     */
    protected function findTree($data,$id=0,$lev=0)
    {
        static $tree=[];
        foreach($data as $k=>$v){
            if($v->cats_pid==$id){
               $v->lev=$lev;
                $tree[]=$v;
                $this->findTree($data,$v->cats_id,$lev+1);
            }
        }
        return $tree;
    } 
    
    public function delete($id)
    {
        $data=\DB::table('cats')->where('cats_id',$id)->delete();
        
            
            return 1;
       
       
            
    }
    /**
     * 退出
     * @return [type]
     */
    public function getLogout()
    {
        Admin::logout();
    }    
}
